import React, { FC, useEffect, useMemo, useState, useRef } from 'react';
import classnames from 'classnames';
import { Search16 } from '@lw36.01/assets/icon';
import './SearchBar.less'
import { ThemeColorProps } from '../../common/interface/navInterface';
// eslint-disable-next-line import/no-cycle
import { SearchResultPop } from './ResultPop'
import { Input } from '../../../components/antd';

// 全局搜索框接收的参数类型
type GlobalSearchPropsType = {
}
export const SearchBar: FC<ThemeColorProps & GlobalSearchPropsType> = (props) => {
    const [popHidden, setPopHidden] = useState(true)
    // 点击输入框
    const inputClick = () => {
        // 如果原来是隐藏的，显示时切到默认的综合tab。
        // 只能在下次显示时切换的原因是，如果在关闭弹窗时就切换，会导致联系人tab的联系人弹窗消失
        if (popHidden) {
            resultPopRef?.current?.setActiveTab('composite'); //重置激活的tab
        }
        setPopHidden(false)
    }
    // 保存输入框的值
    const [keyword, setKeyword] = useState<string>('');
    // 输入框的值变更，添加防抖
    const inputTimer = useRef<number>(0);
    const [value, setValue] = useState('')
    const keywordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        // 超过50个字截断
        const eValue = e.target.value.slice(0, 50);
        // 输入框的值需要及时的显示出来，不能防抖
        setValue(eValue);
        clearTimeout(inputTimer.current)
        inputTimer.current = Number(setTimeout(() => {
            setKeyword(eValue);
        }, 300))
    }
    // keyword变化后更新输入框的值，比如当点击搜索记录时
    useEffect(() => {
        setValue(keyword)
    }, [keyword])
    // 搜索框关闭时清空输入框内容
    useEffect(() => {
        if (popHidden) {
            setKeyword('');
        }
    }, [popHidden])
    const gsearchRef = useRef<any>()
    const bgTimer = useRef<number>(0);
    const resultPopRef = useRef<any>();
    useEffect(() => {
        if (popHidden) {
            return;
        }
        // 按Esc关闭搜索
        const handleEsc = (e: KeyboardEvent) => {
            if (e.code === 'Escape') {
                setPopHidden(true)
            }
        }
        document.addEventListener('keydown', handleEsc)
        // 判断是否点击了当前模块的Modal，如果点击的是搜索框业务中的Modal，不关闭搜索框
        const isModal = (event: MouseEvent, className: string): boolean => {
            const e: any = event;
            let flag = false;
            let times = 0; //向父级查找的最大次数
            const getParentNode = (e: any): void => {
                times += 1;
                if (times > 10) {
                    return;
                }
                if (e?.className?.includes(className)) {
                    flag = true;
                } else if (e && e.parentNode) {
                    getParentNode(e.parentNode)
                }
            }
            if (e.target?.className?.includes(className)) {
                flag = true;
            } else {
                getParentNode(e.target.parentNode)
            }
            return flag;
        }
        // 点击其他地方关闭搜索
        const handleBackgroundClick = (e: MouseEvent) => {
            clearTimeout(bgTimer.current)
            bgTimer.current = window.setTimeout(() => {
                try {
                    const { target } = e;
                    // 点击搜索框业务内部的Modal时不关闭搜索框
                    if (isModal(e, 'gsearch-modal')) {
                        return;
                    }
                    if (gsearchRef.current && gsearchRef.current.contains(target)) {
                        return;
                    }
                    setPopHidden(true);
                } catch (error) {
                    console.error('点击背景关闭搜索报错：', error)
                }
            }, 200)
        }
        document.addEventListener('click', handleBackgroundClick)
        // 组件销毁时注销事件
        return () => {
            document.removeEventListener('keydown', handleEsc);
            document.removeEventListener('click', handleBackgroundClick)
        }
    }, [popHidden])
    // 搜索结果弹窗
    const SearchResultPopNode = useMemo(() => {
        return <SearchResultPop popHidden={popHidden} keyword={keyword} setKeyword={setKeyword} setPopHidden={setPopHidden} ref={resultPopRef} />
    }, [popHidden, keyword])
    return <div className='gsearch-wrap' id='gsearchWrapId' ref={dom => {gsearchRef.current = dom}}>
        <Input
            className={classnames('gsearch-input', {'active': !popHidden})}
            placeholder="搜索应用或帮助"
            value={value}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => keywordChange(e)}
            onClick={() => inputClick()}
            prefix={<Search16 size={16} className="gsearch-input-icon" />}
        />
        { SearchResultPopNode }
    </div>
}